import { defineStore, createPinia } from 'pinia'
import { computed, ref } from 'vue'
import { App } from 'vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import {
  getUserInfoApi,
  getUserAccessRoutesApi,
} from '@/request/api/remoteInteraction'
import {
  getProjectsApi,
  addProjectApi,
  updateProjectApi,
  deleteProjectApi,
} from '@/request/api/project'

const pinia = createPinia()

// 封装路由初始化方法
export const initStore = (app: App<Element>) => {
  app.use(pinia)
}

// 在 Setup Store 中：
// ref() 就是 state 属性
// computed() 就是 getters
// function() 就是 actions

//
//
// 联网状态
export const useOnlineStatusStore = defineStore('onlineStatus', () => {
  const onlineStatus = ref<boolean>(true)
  const refresh = ref<string>()

  function setStatus(value: boolean) {
    onlineStatus.value = value
  }
  function getStatus() {
    return onlineStatus.value
  }

  // 给出联网情况提示变化
  function setRefresh() {
    refresh.value = new Date().toString()
  }

  return {
    onlineStatus: computed(() => onlineStatus.value),
    refresh: computed(() => refresh.value),
    setStatus,
    getStatus,
    setRefresh,
  }
})

//
//
// 用户信息
export const useUserStore = defineStore('user', () => {
  const phone = ref<string>('')
  const email = ref<string>('')
  const userId = ref<string>('')
  const avatar = ref<string>('')
  const account = ref<string>('')
  const nickname = ref<string>('')
  const signature = ref<string>('')
  const createTime = ref<string>('')
  const loginStatus = ref<boolean>(false)

  const routes = ref<RouteItf[]>([])

  async function getUserInfo() {
    const res = await getUserInfoApi()
    if (res.code !== 200) {
      loginStatus.value = false
      window.localStorage.removeItem('token')
      routes.value = []
      return false
    }

    email.value = res.data.email
    userId.value = res.data.id
    phone.value = res.data.phoneNumber
    avatar.value = res.data.avatar
    account.value = res.data.account
    nickname.value = res.data.nickname
    signature.value = res.data.signature
    createTime.value = res.data.createTime
    loginStatus.value = true
    await getUserAccessRoutes()

    return true
  }

  function setLoginStatus() {
    loginStatus.value = false
  }
  function resetData() {
    loginStatus.value = false
    routes.value = []
    userId.value = ''
  }

  // 获取登录用户的系统访问路由
  async function getUserAccessRoutes() {
    const res = await getUserAccessRoutesApi('资源池系统')
    routes.value = res.data
    // console.log(res.data)
    return res.data
  }

  return {
    phone: computed(() => phone.value),
    email: computed(() => email.value),
    userId: computed(() => userId.value),
    avatar: computed(() => avatar.value),
    account: computed(() => account.value),
    nickname: computed(() => nickname.value),
    signature: computed(() => signature.value),
    createTime: computed(() => createTime.value),
    loginStatus: computed(() => loginStatus.value),
    remoteRoutes: computed(() => routes.value),
    resetData,
    getUserInfo,
    setLoginStatus,
    getUserAccessRoutes,
  }
})

//
//
// 用户资源列表
export const useProjectStore = defineStore('project', () => {
  const projectList = ref<ProjectItf[]>([])
  const currentProjectId = ref<string>('')
  const currentProjectName = ref<string>('')
  const currentProjectDesc = ref<string>('')

  // 设置当前项目id
  function setCurrentProjectId(id: string) {
    currentProjectId.value = id
    localStorage.setItem('currentProjectId', id)

    const l = projectList.value.filter((item) => item.id === id)
    currentProjectName.value = l[0]?.name
    currentProjectDesc.value = l[0]?.description
  }

  // 获取项目列表
  async function getProjects() {
    const res = await getProjectsApi()
    if (res.code !== 200) return ElMessage.error('获取项目列表失败！')
    projectList.value = res.data
    if (currentProjectId.value === '') {
      const localID = localStorage.getItem('currentProjectId')
      if (localID) setCurrentProjectId(localID)
      else setCurrentProjectId(projectList.value[0].id)
    }
    // ElMessage.success('获取项目列表成功！')
  }

  // 新增项目
  async function addProject(name: string, desc: string) {
    const res = await addProjectApi(name, desc)
    if (res.code !== 200) return ElMessage.error('新增项目失败！')
    ElMessage.success('新增项目成功！')
    getProjects()
  }

  // 更新项目信息
  async function updateProject(name: string, desc: string): Promise<boolean> {
    const res = await updateProjectApi(currentProjectId.value, name, desc)
    if (res.code !== 200) return false
    await getProjects()
    setCurrentProjectId(currentProjectId.value)
    return true
  }

  // 删除项目
  async function deleteProject(): Promise<boolean> {
    const res = await deleteProjectApi(currentProjectId.value)
    if (res.code !== 200) return false
    currentProjectId.value = ''
    getProjects()
    return true
  }

  return {
    projectList: computed(() => projectList.value),
    currentProjectId: computed(() => currentProjectId.value),
    currentProjectName: computed(() => currentProjectName.value),
    currentProjectDesc: computed(() => currentProjectDesc.value),
    setCurrentProjectId,
    getProjects,
    addProject,
    updateProject,
    deleteProject,
  }
})
